package app.foo.gfbosurfaceview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import androidx.annotation.NonNull;

/**
 * surfaceView是View子类，常用于更新比较快的界面
 * surfaceHolder.callback surfaceView 的生命周期的回调接口
 * View.OnTouchListener 触摸事件
 * SensorEventListener 传感事件：重力加速度计
 **/

public class GameView extends SurfaceView implements SurfaceHolder.Callback,View.OnTouchListener, SensorEventListener {
    private SurfaceHolder holder;//SurfaceView的托管类
    private Canvas canvas;//画布
    private Paint paint;//画笔

    private int screenWidth, screenHeight;//屏幕尺寸相关参数
    private float x, y, radius = 10;//圆相关参数

    private boolean threadFlag;//线程管理的标志
    private float speed = 1.0f;//每秒25帧
    private int direction = 1;//圆变化的方向

    private SensorManager sm;//传感器管理类
    private float[]accelerometerValues=new float[3];//加速度传感数据
    private float[]manageticFieldValues=new float[3];//地磁传感数据

    public GameView(Context context) {
        super(context);
        holder = getHolder();//获取当前SurfaceView的托管对象
        holder.addCallback(this);//加载生命周期回调接口

        paint = new Paint();

        screenWidth = this.getResources().getDisplayMetrics().widthPixels;
        screenHeight = this.getResources().getDisplayMetrics().heightPixels;

        //圆坐标
        x = screenWidth / 2;
        y = screenHeight / 2;

        //设置触摸监听
        setOnTouchListener(this);

        //注册传感器
        //三个参数：活动，传感器类型，传感器工作方式
        sm= (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        sm.registerListener(this,
                sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME);
        sm.registerListener(this,
                sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {

        threadFlag = true;//设置线程启动标志
        new DrawThread().start();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {

    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        x= motionEvent.getRawX();
        y=motionEvent.getRawY();
        return true;
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        //获取对应的传感数据
        if(sensorEvent.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
            accelerometerValues=sensorEvent.values;
        }
        if(sensorEvent.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){
            manageticFieldValues=sensorEvent.values;
        }
        //数据处理：矩阵的变换
        float[]values=new float[3];
        float[]r=new  float[9];
        SensorManager.getRotationMatrix(r,null,accelerometerValues,manageticFieldValues);
        SensorManager.getOrientation(r,values);
        values[1]=(float) Math.toDegrees(values[1]);
        values[2]=(float) Math.toDegrees(values[2]);
        //移动小球
        if(values[2]>0&&x<screenWidth)x+=5;//右移
        if(values[2]<0&&x>0)x-=5;//左移
        if(values[1]>0&&y>0)y-=5;//上移
        if(values[1]<0&&y<screenHeight)y+=5;//下移

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    private class DrawThread extends Thread {
        @Override
        public void run() {
            while (threadFlag) {

                long _startTime = System.currentTimeMillis();

                canvas = holder.lockCanvas();//获取当前画布并锁定
                draw();//界面控制
                logic();//逻辑控制

                holder.unlockCanvasAndPost(canvas);//释放画布并提交刷新界面

                long _endTime = System.currentTimeMillis();
                long _sleepTime = (long) speed * 40 - (_endTime - _startTime);
                if (_sleepTime > 0) {
                    try {
                        Thread.sleep(_sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    private void draw() {
        //设置画笔清除与重绘的模式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        canvas.drawPaint(paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
        //绘制矩形背景
        paint.setColor(Color.WHITE);
        canvas.drawRect(0, 0, screenWidth, screenHeight, paint);
        //绘制圆形
        paint.setColor(Color.RED);
        canvas.drawCircle(x, y, radius, paint);
    }

    private void logic() {
        radius += 5 * direction;
        if (radius >= 100 || radius <= 10) {
            direction *= -1;
           }
        }
    }
}

